package org.zjx.app.action.gather;


import org.zjx.analysis.analyze.window.impl.TaskBoxAnalysis;
import org.zjx.app.action.AbstractWindowAction;
import org.zjx.command.entity.Quest;
import org.zjx.command.state.QuestState;
import org.zjx.window.window.IWindow;

import java.awt.*;
import java.util.Map;

public class GatherTaskBoxAction extends AbstractWindowAction {
    private TaskBoxAnalysis taskBoxAnalysis;

    public GatherTaskBoxAction(IWindow targetWindow) {
        super(targetWindow);
        analysis();
    }

    private void analysis() {
        taskBoxAnalysis = new TaskBoxAnalysis(targetWindow);
    }

    @Override
    public void open() {
        mouseAloofWindow(taskBoxAnalysis.windowArea == null? taskBoxAnalysis.getOriginBounds(): taskBoxAnalysis.windowArea);
        if (taskBoxAnalysis.isOpened()) return;
        Rectangle rectangle = taskBoxAnalysis.conversion(taskBoxAnalysis.getOriginBounds(),taskBoxAnalysis.areaMap.get("打开").getRectangle());
        targetWindow.actions().clickIn(rectangle);
        targetWindow.flushScreenshot();
        analysis();
        open();
    }

    @Override
    public void close() {
        analysis();
        if (!taskBoxAnalysis.isOpened()) return;
        Rectangle rectangle = taskBoxAnalysis.conversion(taskBoxAnalysis.windowArea,taskBoxAnalysis.areaMap.get("关闭").getRectangle());
        targetWindow.actions().clickIn(rectangle);
        targetWindow.flushScreenshot();
        close();
    }

    @Override
    public void reSetWindow() {

    }

    @Override
    public void mouseAloofWindow(Rectangle rect) {
        if (taskBoxAnalysis.mouseInRect(rect)) {
            Point safePoint = taskBoxAnalysis.findLargestRemainingAreaCenter(rect);
            targetWindow.actions().gameMoveTo(safePoint.x, safePoint.y).delay(200);
            targetWindow.flushScreenshot();
            analysis();
        }
    }

    @Override
    protected void doExecute() throws Exception {
        open();
        reSetWindow();
        QuestState questState = new QuestState();
        stateManager.registerState(questState);

        Map<String, Quest> quests = taskBoxAnalysis.getQuests();
        questState.setQuests(quests);

//        close();
    }
}
